<template>
  <!-- 新增角色 -->
  <el-dialog
    :title="handleType=='add'?'新增角色':'修改角色'"
    :visible.sync="visible"
    :before-close="handleClose"
  >
    <div class="scroll-y" v-loading="loading">
      <el-form label-width="80px" :model="handleForm" size="small" ref="handleForm">
        <el-form-item
          label="角色名称"
          prop="roleName"
          :rules="[ { required: true, message: '角色名称不能为空',trigger:'blur'},
            { max: 10, message: '角色名称不能超过10个字符',trigger:'blur'}]"
        >
          <el-input v-model.trim="handleForm.roleName" show-word-limit maxlength="10"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="description">
          <el-input type="textarea" :rows="4" v-model="handleForm.description" show-word-limit maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <PermissionSelect
        :checkArr="resource"
        @getChecked="getChecked"
        class="mt-20"
        v-if="resource.length>0"
      />
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="submit">{{handleType=='add'?'立即创建':'修改角色'}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import PermissionSelect from "../../components/PermissionSelect";
import {
  getResourceAll,
  getRoleResourceList,
  roleAdd,
  roleUpdate
} from "api/seting/role";

export default {
  components: {
    PermissionSelect
  },
  props: ["visible", "handleType", "roleRow"],
  data() {
    return {
      handleForm: {
        roleName: "",
        description: ""
      },
      loading: false,
      resource: []
    };
  },
  created() {
    this.loadResourceAll();
  },
  mounted() {
    this.$watch(
      "roleRow",
      function(val, oldVal) {
        if (val != oldVal) {
          this.handleForm.id = val.id;
          this.handleForm.roleName = val.roleName;
          this.handleForm.description = val.description;
          this.loadRoleResource();
        }
      },
      { immediate: true }
    );
  },
  methods: {
    loadResourceAll() {
      getResourceAll({})
        .then(res => {
          let data = res.data;
          let resource = this.unique(data);
          this.resource = this.remixed(resource, data);
        })
        .catch(err => {});
    },
    loadRoleResource() {
      if (!this.roleRow.id) return;
      this.loading = true;
      getRoleResourceList({ roleId: this.roleRow.id })
        .then(res => {
          this.resource.map(o => {
            let ids = [];
            res.data.forEach(i => {
              if (i.moduleCode === o.moduleCode) {
                ids.push(i.resourceId);
              }
            });
            o.checked = ids;
            o.isIndeterminate =
              ids.length > 0 && ids.length < o.children.length;
            o.checkedAll = ids.length == o.children.length;
            return o;
          });
          this.loading = false;
        })
        .catch(err => {});
    },
    unique(arr) {
      // 数组去重
      let obj = {};
      let resource = arr.reduce((o, next) => {
        obj[next.moduleCode]
          ? ""
          : (obj[next.moduleCode] =
              true &&
              o.push({
                moduleCode: next.moduleCode,
                moduleName: next.moduleName
              }));
        return o;
      }, []);
      return resource;
    },
    remixed(parent, arr) {
      if (parent.length == 0 || arr.length == 0) return;
      let resource = parent.map(o => {
        let children = new Array();
        arr.forEach(i => {
          i.resourceId = i.id;
          if (i.moduleCode === o.moduleCode) {
            children.push(i);
          }
        });
        o.checked = [];
        o.isIndeterminate = false;
        o.checkedAll = false;
        o.children = children;
        return o;
      });
      return resource;
    },
    // 关闭弹框
    handleClose(done) {
      this.$parent.visible = false;
      this.$parent.roleRow = {};
    },
    getChecked(ids) {
      this.handleForm.resourceIds = ids;
    },
    // 新增 编辑角色
    submit() {
      this.$refs.handleForm.validate(valid => {
        if (valid) {
          let request = this.handleType == "add" ? roleAdd : roleUpdate;
          request(this.handleForm)
            .then(res => {
              this.$parent.visible = false;
              this.$message.success("操作成功");
              this.$parent.init();
              this.$refs.handleForm.resetFields();
            })
            .catch(err => {
              this.$message.error(err.msg);
            });
        } else {
          console.log("error submit!!");
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.scroll-y {
  max-height: 50vh;
  overflow: auto;
}
</style>
